<?php

namespace addons\wwh\controller;

use think\Db;
use think\Request;
use addons\wwh\model\Column as ColumnModel;

class Column extends Base
{
    public function index()
    {
        // 初始化并验证参数
        $diyname = $this->request->param('diyname/s');
        if (empty($diyname)) {
            $this->error('参数错误！');
        }

        // 获取当前栏目信息
        $navCur = $this->getCurrentColumn($diyname);
        $this->view->assign([
            'navCur' => $navCur,
            'currentId' => $navCur['id'],
            'secondId' => ColumnModel::getSecondId($navCur['id']) // 获取第二级栏目ID
        ]);

        // 处理跳转链接
        if ($navCur['type'] === 'link') {
            $this->redirect($navCur['outlink']);
        }

        // 获取顶级栏目
        $topId = ColumnModel::getTopColumn($navCur);
        $this->view->assign('top', $topId);

        // 确定模板
        $template = $this->getTemplate($navCur);

        // 加载各模块数据
        $this->loadContentList($navCur);       // 内容列表
        $this->loadDownloadList();             // 资料下载
        $this->loadServiceData();              // 服务策略
        $this->loadFaqList();                  // 常见问题
        $this->loadQualityAssurance();         // 质保查询
        $this->loadPartnerList();              // 合作伙伴
        $this->loadAboutData();                // 公司概况
        $this->loadDevelopmentData();          // 发展历程
        $this->loadHonorList();                // 荣誉资质
        $this->loadJoinUsData();               // 加入我们
        $this->loadContactData();              // 联系我们

        return $this->view->fetch('/' . $template);
    }

    /**
     * 获取当前栏目信息
     */
    protected function getCurrentColumn($diyname)
    {
        $column = Db::name('wwh_column')
            ->where('diyname', $diyname)
            ->where('lang', $this->lang)
            ->find();

        if (!$column) {
            $this->error('栏目不属于当前语言或未知栏目！');
        }

        return $column;
    }

    /**
     * 获取模板名称
     */
    protected function getTemplate($navCur)
    {
        $template = preg_replace('/\.html$/', '', $navCur['listtpl']);
        if (!$template) {
            $template = preg_replace('/\.html$/', '', $navCur['showtpl']);
        }
        return $template;
    }

    /**
     * 加载内容列表
     */
    protected function loadContentList($navCur)
    {
        $archivesQuery = Db::name('wwh_archives')
            ->where('lang', $this->lang)
            ->where('status', '1')
            ->order('weigh desc');

        if ($navCur) {
            $archivesQuery->where('type', $navCur['classify'])
                ->whereRaw('find_in_set('.$navCur['id'].', `column_ids`)');
        }

        $list = $archivesQuery->paginate(9, false, ['query' => request()->param()]);

        $this->assign([
            'archives' => $list,
            'lbPage' => $list->render()
        ]);
    }

    /**
     * 加载资料下载列表
     */
    protected function loadDownloadList()
    {
        $downkeys = trim(input('downkeys', ''));
        $category = trim(input('category', ''));

        $query = Db::name('wwh_archives')
            ->where('status', '1')
            ->where('type', 'download')
            ->where('lang', $this->lang)
            ->order('weigh desc');

        if ($downkeys !== '' || $category !== '') {
            if ($downkeys !== '') {
                $query->where('title', 'like', '%' . $downkeys . '%');
            }
            if ($category !== '') {
                $query->where('column_id', $category);
            }
        }

        $list = $query->paginate(8, false, ['query' => request()->param()]);

        $this->assign([
            'down' => $list,
            'downPage' => $list->render(),
            'downType' => [
                1 => __lang('Manual'),
                2 => __lang('Color Page'),
                3 => __lang('Driver'),
                4 => __lang('Other')
            ]
        ]);
    }

    /**
     * 加载服务策略数据
     */
    protected function loadServiceData()
    {
        $service = Db::name('wwh_service')
            ->where('lang', $this->lang)
            ->find();

        $this->assign('service', $service ?: []);
    }

    /**
     * 加载常见问题列表
     */
    protected function loadFaqList()
    {
        $faqkeys = trim(input('faqkeys', ''));

        // 构建基础查询
        $query = Db::name('wwh_faq')
            ->where('status', '1')
            ->where('lang', $this->lang);

        // 应用搜索条件
        if (!empty($faqkeys)) {
            $query->where('title', 'like', '%'.$faqkeys.'%');
        }

        // 获取分页列表
        $list = $query->order('weigh desc')
            ->paginate(8, false, ['query' => request()->param()]);

        // 获取总数
        $faqCount = $list->total();

        $this->assign([
            'faq' => $list,
            'faqPage' => $list->render(),
            'faqCount' => $faqCount
        ]);
    }

    /**
     * 加载质保查询数据
     */
    protected function loadQualityAssurance()
    {
        $qakeys = trim(input('get.qakeys', ''));
        $isSearchRequest = request()->has('qakeys');

        if ($isSearchRequest) {
            if (empty($qakeys)) {
                $this->error('请输入序列号');
            }

            $qa = Db::name('wwh_qa')
                ->where('sn', $qakeys)
                ->where('lang', $this->lang)
                ->select();

            $this->assign([
                'qa' => $qa,
                'showNoQa' => empty($qa)
            ]);
        } else {
            $this->assign('showNoQa', false);
        }
    }

    /**
     * 加载合作伙伴列表
     */
    protected function loadPartnerList()
    {
        $list = Db::name('wwh_partner')
            ->where('lang', $this->lang)
            ->order('weigh desc')
            ->paginate('24', false, ['query' => request()->param()]);

        $this->assign([
            'partner' => $list,
            'partnerPage' => $list->render()
        ]);
    }

    /**
     * 加载公司概况数据
     */
    protected function loadAboutData()
    {
        $about = Db::name('wwh_about')
            ->where('lang', $this->lang)
            ->find();

        $this->assign('about', $about ?: []);
    }

    /**
     * 加载发展历程数据
     */
    protected function loadDevelopmentData()
    {
        $development = Db::name('wwh_development')
            ->where('lang', $this->lang)
            ->order('id asc')
            ->select();

        $this->assign('development', $development ?: []);
    }

    /**
     * 加载荣誉资质列表
     */
    protected function loadHonorList()
    {
        $list = Db::name('wwh_honor')
            ->where('lang', $this->lang)
            ->order('weigh desc')
            ->paginate('9', false, ['query' => request()->param()]);

        $this->assign([
            'honor' => $list,
            'honorPage' => $list->render(),
            'honorType' => [
                1 => __lang('Qualifications'),
                2 => __lang('Honor'),
                3 => __lang('Other')
            ]
        ]);
    }

    /**
     * 加载加入我们数据
     */
    protected function loadJoinUsData()
    {
        // 部门和地址列表
        $deptList = Db::name('wwh_position')
            ->where('lang', $this->lang)
            ->distinct(true)
            ->field('dept')
            ->select();

        $addrList = Db::name('wwh_position')
            ->where('lang', $this->lang)
            ->distinct(true)
            ->field('addr')
            ->select();

        $this->assign([
            'deptList' => $deptList ?: [],
            'addrList' => $addrList ?: [],
        ]);

        // 职位查询
        $jonKeywords = trim(input('jonKeywords', ''));
        $branch = trim(input('branch', ''));
        $address = trim(input('address', ''));

        $query = Db::name('wwh_position')
            ->where('lang', $this->lang)
            ->order('time desc');

        if (!empty($jonKeywords) || !empty($branch) || !empty($address)) {
            $conditions = [];
            if (!empty($jonKeywords)) {
                $conditions['name'] = ['like', "%{$jonKeywords}%"];
            }
            if (!empty($branch)) {
                $conditions['dept'] = $branch;
            }
            if (!empty($address)) {
                $conditions['addr'] = $address;
            }
            $query->where($conditions);
        }

        $list = $query->paginate(6, false, ['query' => request()->param()]);

        $this->assign([
            'join' => $list,
            'joinPage' => $list->render()
        ]);
    }

    /**
     * 加载联系我们数据
     */
    protected function loadContactData()
    {
        $market = Db::name('wwh_market')
            ->where('lang', $this->lang)
            ->order('weigh desc')
            ->select() ?: [];

        $contact = Db::name('wwh_contact')
            ->where('lang', $this->lang)
            ->find();

        $this->assign([
            'contact' => $contact ?: [],
            'market' => $market ?: []
        ]);
    }
}
